# -*- coding: utf-8 -*-
#coding=utf-8

import web
import os
import config
from action.admin.base import adminAction
from model.image import image
from model.category import category
from model.album import album

'''
Admin controller: producing category administration views.
'''
class refererAction(adminAction):
    def __init__(self, name = '分类管理'):
        adminAction.__init__(self, name)


    def GET(self, name):
        if name == 'list':
            return self.list()
        elif name == 'delete':
            return self.delete()
        elif name == 'add':
            return self.add()
        elif name == 'edit':
            return self.edit()
        else:
            return self.notFound()

    def POST(self, name):
        if name == 'save':
            return self.save()
        elif name == 'modify':
            return self.modify()
        else:
            return self.notFound()

    def list(self):
        inputParams = self.getInput()
        page = int(inputParams['page']) if inputParams.has_key('page') else 1
        count = config.COUNT_PER_PAGE
        offset= (page-1)*count if page > 0 else 0
   
        condition = {}
        categoryObj = category()
        listData = categoryObj.getOne('COUNT(*) AS `total`', condition)
        totalCount = listData['total']
        categoryList = categoryObj.getList('*', condition, '', str(offset) + ',' + str(count))
        pageString = self.getPageStr(self.makeUrl('/admin/category/list'), page, count, totalCount)
        self.privData['CATEGORY_LIST'] = categoryList
        self.privData['PAGE_STRING'] = pageString

        return self.display('categoryList')

    def delete(self):
        inputParams = self.getInput()

        try:
            condition = { 'id': int(inputParams['id']) }
            category().delete(condition)
        except Exception, e:
            return self.error(msg = '分类删除失败: %s' % e, url=self.makeUrl('/admin/category/list'))
    
        return self.success(msg='分类删除成功', url=self.makeUrl('/admin/category/list'))

    def add(self):
        condition = {}
        albumList = album().getList('*', condition)
        self.privData['ALBUM_LIST'] = {}
        for item in albumList:
            self.privData['ALBUM_LIST'][item['id']] = item['name']

        self.privData['IMG_ALBUM_LIST'] = {}
        for i in albumList:
            self.privData['IMG_ALBUM_LIST'][i['id']] = {};
            imageList = image().getList('*',{'album': i['id']}, orders="id asc")
            for img in imageList:
                self.privData['IMG_ALBUM_LIST'][i['id']][img['id']] = img['desc']

        self.privData['CURRENT_ALBUM'] = 1
        self.privData['CURRENT_IMG'] = 1
        self.privData['SUBMIT_NAME'] = "thumbnail"

        return self.display('categoryAdd')
    
    def modify(self):
        inputParams= self.getInput()

        try:
            data={
                'name':         inputParams['name'],
                'desc':         inputParams['desc'],
                'seq':          int(inputParams['seq']),
                'thumbnail':    int(inputParams['thumbnail']),
            }
            category().update(data, {'id': int(inputParams['id'])})
        except Exception, e:
            return self.error(msg = '分类修改失败: %s' % e, url=self.makeUrl('/admin/category/list'))

        return self.success('分类修改成功', url=self.makeUrl('/admin/category/list'))

    def edit(self):
        inputParams = self.getInput()

        categoryObj = category().getOne('*', {'id': int(inputParams['id'])})
        if not categoryObj:
            return self.error(msg = '分类不存在', url=self.makeUrl('/admin/category/list'))

        self.privData['CATEGORY_ID'] =   categoryObj['id']
        self.privData['CATEGORY_NAME'] = categoryObj['name']
        self.privData['CATEGORY_DESC'] = categoryObj['desc']
        self.privData['CATEGORY_SEQ'] = categoryObj['seq']

        condition = {}
        albumList = album().getList('*', condition)
        self.privData['ALBUM_LIST'] = {}
        for item in albumList:
            self.privData['ALBUM_LIST'][item['id']] = item['name']

        self.privData['IMG_ALBUM_LIST'] = {}
        for i in albumList:
            self.privData['IMG_ALBUM_LIST'][i['id']] = {};
            imageList = image().getList('*',{'album': i['id']}, orders="id asc")
            for img in imageList:
                self.privData['IMG_ALBUM_LIST'][i['id']][img['id']] = img['desc'] 

        self.privData['SUBMIT_NAME'] = "thumbnail"
        self.privData['CURRENT_ALBUM'] = 1
        self.privData['CURRENT_IMG'] = categoryObj['thumbnail']

        return self.display('categoryEdit')


    def save(self):
        userInput= self.getInput()  
        try:
            data = {
                'name':         userInput['name'],
                'desc':         userInput['desc'],
                'seq':          int(userInput['seq']),
                'thumbnail':    int(userInput['thumbnail']),
            }
            category().insert(data)
        except Exception, e:
            return self.error(msg = '分类保存失败: %s' % e, url=self.makeUrl('/admin/category/list'))
        return self.success('分类保存成功', url=self.makeUrl('/admin/category/list'))
